package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"time"
)

func main() {
	RedisInit()
	defer RedisClose()

	var err error
	_, err = Rds.Do("set", "terminal_info2:name", "abc") //redis set命令
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err = Rds.Do("set", "terminal_info2:name2", "abc2") //redis set命令
	if err != nil {
		fmt.Println(err)
		return
	}

	res, err := Rds.Do("Get", "terminal_info2:name") //redis get命令
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("res:", res)

	res1, err := redis.String(Rds.Do("Get", "terminal_info2:name2")) //redis get命令
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("res1:", res1)

	res2, err := redis.Int(Rds.Do("Get", "name")) //redis get命令
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("res2:", res2)
}

var Rds redis.Conn

/*func GetAllKeys() {
	var cursor uint64
	for {
		var keys []string
		var err error
		keys, cursor, err = rdb.Scan(ctx, cursor, "prefix:*", 0).Result()
		if err != nil {
			panic(err)
		}

		for _, key := range keys {
			fmt.Println("key", key)
		}

		if cursor == 0 { // no more keys
			break
		}
	}
}*/

func RedisPollInit() *redis.Pool {
	return &redis.Pool{
		MaxIdle:     5, //最大空闲数
		MaxActive:   0, //最大连接数，0不设上
		Wait:        true,
		IdleTimeout: time.Duration(1) * time.Second, //空闲等待时间
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", "127.0.0.1:6379") //redis IP地址
			_, err2 := c.Do("SELECT", 1)
			if err2 != nil {
				c.Close()
				return nil, err2
			}
			if err != nil {
				fmt.Println(err)
				return nil, err
			}
			redis.DialDatabase(1)
			return c, err
		},
	}
}

func RedisInit() {
	Rds = RedisPollInit().Get()
}

func RedisClose() {
	_ = Rds.Close()
}
